def KSA(key):
    """密钥调度算法 (Key Scheduling Algorithm)"""
    key_length = len(key)
    S = list(range(256))
    j = 0
    for i in range(256):
        j = (j + S[i] + key[i % key_length]) % 256
        S[i], S[j] = S[j], S[i]
    return S

def PRGA(S):
    """伪随机数生成算法 (Pseudo-Random Generation Algorithm)"""
    i = 0
    j = 0
    while True:
        i = (i + 1) % 256
        j = (j + S[i]) % 256
        S[i], S[j] = S[j], S[i]
        K = S[(S[i] + S[j]) % 256]
        yield K

def RC4(key, ciphertext):
    """RC4 解密函数"""
    S = KSA(key)
    keystream = PRGA(S)
    plaintext = bytearray()
    for byte in ciphertext:
        decrypted_byte = byte ^ next(keystream)
        plaintext.append(decrypted_byte)
    return bytes(plaintext)

def main():
    key = input("请输入密钥: ").encode('utf-8')
    ciphertext_hex = input("请输入密文 (十六进制): ")

    # 将十六进制字符串转换为字节
    ciphertext = bytes.fromhex(ciphertext_hex)

    # 解密
    decrypted_text = RC4(key, ciphertext)
    print(f"解密后的明文: {decrypted_text.decode('utf-8')}")

if __name__ == "__main__":
    main()
